// pages/service-guide/service-guide.js
Page({
  data: {
    // 从后端加载的就诊指南数据（分组渲染）
    guides: [],
    showModal: false,
    modalTitle: '',
    modalContent: ''
  },

  onLoad(options) {
    // 页面加载时执行
    this.fetchGuides();
  },

  // 从后端获取就诊指南（单表）
  fetchGuides() {
    const that = this;
    wx.request({
      url: 'http://localhost:8004/visit-guide/all',
      method: 'GET',
      success(res) {
        if (res.data && res.data.code === 200) {
          const list = res.data.data || [];
          console.log('获取到的原始数据:', list);
          
          // 分组映射：{category_code: {name, items:[]}}
          const groupMap = {};
          list.forEach(item => {
            const code = item.categoryCode;
            if (!groupMap[code]) {
              groupMap[code] = {
                categoryName: item.categoryName,
                categoryCode: code,
                categoryOrder: item.categoryOrder,
                items: []
              };
            }
            groupMap[code].items.push(item);
          });
          
          const guides = Object.values(groupMap).sort((a,b) => a.categoryOrder - b.categoryOrder);
          console.log('处理后的分组数据:', guides);
          
          that.setData({ guides });
        } else {
          console.error('获取就诊指南失败', res.data);
        }
      },
      fail(err) {
        console.error('获取就诊指南失败', err);
      }
    });
  },

  // 动态项点击：content型弹窗，page型跳转
  onItemTap(e) {
    const item = e.currentTarget.dataset.item;
    console.log('点击的项目:', item);
    
    if (!item) {
      console.error('项目数据为空');
      return;
    }
    
    console.log('renderType:', item.renderType);
    console.log('pagePath:', item.pagePath);
    console.log('content:', item.content);
    
    if (item.renderType === 'page' && item.pagePath) {
      console.log('跳转到页面:', item.pagePath);
      wx.navigateTo({ url: item.pagePath });
    } else if (item.renderType === 'content' && item.content) {
      console.log('显示内容弹窗:', item.itemTitle);
      this.setData({
        showModal: true,
        modalTitle: item.itemTitle,
        modalContent: item.content
      });
    } else {
      console.log('显示默认弹窗');
      this.setData({
        showModal: true,
        modalTitle: item.itemTitle,
        modalContent: item.content || '暂无内容'
      });
    }
  },

  closeModal() {
    this.setData({ showModal: false });
  },

  noop() {}
});
